<?php

namespace App\Http\Controllers\Manager;

use App\Http\Controllers\Controller;
use App\Models\Server;
use App\Models\Video;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Exception;

class VideoController extends Controller
{
    public $prefix='manager.server';
    /**
     * @param $id
     * @return mixed
     * @throws Exception
     */
    protected function CheckServer($id){
        $server=Server::find($id);
        $uid=Auth::user()->id;
        if ($server->user_id==$uid){
            return $server;
        }else{
            throw new Exception('无权访问次服务器',401);
        }
    }

    public function video($id){
        $server=$this->CheckServer($id);
        return view($this->prefix.'.video',compact('server'));
    }

    public function videoList($id){
        $server=$this->CheckServer($id);
        $list=$server->videos;
        return JsonResponse::create(['err'=>0, 'res'=>$list]);
    }
    public function videoAdd(Request $request,$id){
        $server=$this->CheckServer($id);
        $data=$request->all();
        $data['server_id']=$server->id;
        $item=Video::create($data);
        return JsonResponse::create(['err'=>0, 'res'=>$item]);
    }

    public function videoUpdate(Request $request,$id){
        $server=$this->CheckServer($id);
        $data=$request->all();
        $item=Video::find($data['id']);
        $item->title=$data['title'];
        $item->url=$data['url'];
        $item->sort=$data['sort'];
        $item->status=$data['status'];
        $item->save();
        return JsonResponse::create(['err'=>0, 'res'=>$item]);
    }

    public function videoDel(Request $request,$id){
        $server=$this->CheckServer($id);
        $data=$request->all();
        $item=Video::find($data['id']);
        $item->delete();
        return JsonResponse::create(['err'=>0]);
    }
}
